package com.cauli.netdisk.module.login.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cauli.netdisk.base.exception.MyException;
import com.cauli.netdisk.module.config.model.dto.ConfigDTO;
import com.cauli.netdisk.module.config.service.ConfigService;
import com.cauli.netdisk.module.login.model.dto.LoginRequestDTO;
import com.cauli.netdisk.module.login.service.ImgVerifyCodeService;
import com.cauli.netdisk.module.login.service.LoginService;
import com.cauli.netdisk.module.user.model.entity.User;
import com.cauli.netdisk.module.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author Cauli
 * @date 2022/12/13 10:04
 * @description 登录 服务实现类
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Resource
    private ConfigService configService;

    @Autowired
    private UserService userService;

    @Resource
    private ImgVerifyCodeService imgVerifyCodeService;

    @Override
    public SaTokenInfo login(LoginRequestDTO loginRequestDTO) {
        // 获取系统设置, 如果缓存中有, 则去缓存取, 没有则查询数据库并写入到缓存中.
        ConfigDTO config = configService.getConfig();
        Boolean captchaMode = config.getCaptchaMode();
        if (captchaMode == true) {
            imgVerifyCodeService.checkCaptcha(loginRequestDTO.getVerifyCodeUUID(), loginRequestDTO.getVerifyCode());
        }
//        LoginVerifyModeEnum loginVerifyMode = config.getLoginVerifyMode();
//        if (Objects.equals(loginVerifyMode, LoginVerifyModeEnum.IMG_VERIFY_MODE)) {
//            imgVerifyCodeService.checkCaptcha(loginRequestDTO.getVerifyCodeUUID(), loginRequestDTO.getVerifyCode());
//        }

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, loginRequestDTO.getUsername())
                .eq(User::getPassword, SecureUtil.md5(loginRequestDTO.getPassword()));
        User user = userService.getOne(queryWrapper);
        if (user == null) {
            throw new MyException("账号或密码错误");
        }
        StpUtil.login(user.getUserId());
        return StpUtil.getTokenInfo();
    }
}
